// 页面加载完成后执行
document.addEventListener('DOMContentLoaded', function() {
    // 初始化所有模块
    initTabs();
    initFilterOptions();
    initLikeButtons();
    initApplyButtons();
    initConsultButtons();
    initTabBar();
    handleImageErrors();
    
    // 预加载图片
    preloadImages();
    
    // 添加用户头像
    const avatarContainer = document.querySelector('.avatar');
    if (avatarContainer) {
        const avatarImg = document.createElement('img');
        avatarImg.src = preloadedImages.avatars[0];
        avatarImg.alt = '用户头像';
        avatarImg.classList.add('user-avatar');
        avatarContainer.appendChild(avatarImg);
        
        // 设置头像样式
        avatarImg.style.width = '100%';
        avatarImg.style.height = '100%';
        avatarImg.style.borderRadius = '50%';
        avatarImg.style.objectFit = 'cover';
    }
    
    // 初始化院校与企业卡片的点击事件
    initInstitutionCardEvents();
    
    // 初始化页面进入动画
    initPageTransitions();
    
    // 隐藏滚动时的底部导航栏
    handleScrollNavigation();
    
    // 设置初始的滑动方向
    loadPageDirection();

    // 添加"加载更多"按钮事件处理
    const loadMoreBtn = document.querySelector('.load-more-btn');
    if (loadMoreBtn && !loadMoreBtn.getAttribute('href')) {
        loadMoreBtn.addEventListener('click', function() {
            // 模拟加载更多，实际项目中应该从服务器加载更多数据
            window.location.href = 'recommend-agents.html';
        });
    }
});

// 标签切换功能
function initTabs() {
    const tabContainers = document.querySelectorAll('.filter-tabs, .module-header .tabs');
    
    tabContainers.forEach(container => {
        const tabs = container.querySelectorAll('.tab');
        
        tabs.forEach(tab => {
            tab.addEventListener('click', function() {
                // 移除当前容器内所有标签的active类
                tabs.forEach(t => t.classList.remove('active'));
                // 为当前点击的标签添加active类
                this.classList.add('active');
                
                // 如果是活动模块的标签，切换显示不同类型的活动
                if (container.closest('.activities')) {
                    const tabText = this.textContent.trim();
                    const activityCards = document.querySelectorAll('.activity-card');
                    
                    // 先隐藏所有活动卡片
                    activityCards.forEach(card => {
                        card.style.display = 'none';
                    });
                    
                    // 如果是全部标签，显示所有活动
                    if (tabText === '全部') {
                        activityCards.forEach(card => {
                            card.style.display = 'block';
                        });
                        return;
                    }
                    
                    // 根据标签类型显示对应活动
                    const activityType = getActivityTypeByTabText(tabText);
                    
                    // 如果没有现有的活动卡片，则创建新的活动卡片
                    if (document.querySelectorAll(`.activity-card[data-type="${activityType}"]`).length === 0) {
                        // 创建对应类型的活动卡片
                        createActivityCardsByType(activityType, container.closest('.activities').querySelector('.card-container'));
                    } else {
                        // 显示对应类型的活动卡片
                        document.querySelectorAll(`.activity-card[data-type="${activityType}"]`).forEach(card => {
                            card.style.display = 'block';
                        });
                    }
                }
                
                // 如果是院校与企业的标签，切换显示内容
                if (container.closest('.institutions')) {
                    const tabText = this.textContent.trim();
                    const institutionCards = document.querySelectorAll('.institution-card');
                    
                    institutionCards.forEach(card => {
                        if (tabText === '热门高校' && card.querySelector('h3').textContent.includes('大学')) {
                            card.style.display = 'block';
                        } else if (tabText === '知名企业' && !card.querySelector('h3').textContent.includes('大学')) {
                            card.style.display = 'block';
                        } else {
                            card.style.display = 'none';
                        }
                    });
                }
            });
        });
    });
    
    // 根据标签文本确定活动类型
    function getActivityTypeByTabText(tabText) {
        switch (tabText) {
            case '职业讲座':
                return 'lecture';
            case '企业开放日':
                return 'openday';
            case '技能竞赛':
                return 'competition';
            default:
                return 'all';
        }
    }
    
    // 创建对应类型的活动卡片
    function createActivityCardsByType(activityType, container) {
        // 活动数据
        const activityData = {
            lecture: [
                {
                    id: 'l1',
                    title: '职场晋升策略与领导力提升讲座',
                    img: 'img/activity-lecture1.jpg',
                    alt: '职场晋升策略与领导力提升讲座',
                    status: 'upcoming',
                    statusText: '即将开始',
                    date: '2023-05-10 19:00',
                    location: '线上',
                    participants: 256
                },
                {
                    id: 'l2',
                    title: '金融行业职业发展路径分享',
                    img: 'img/activity-lecture2.jpg',
                    alt: '金融行业职业发展路径分享',
                    status: 'ongoing',
                    statusText: '进行中',
                    date: '2023-04-28 14:30',
                    location: '北京金融中心',
                    participants: 189
                },
                {
                    id: 'l3',
                    title: 'AI时代的职业规划与转型',
                    img: 'img/activity-lecture3.jpg',
                    alt: 'AI时代的职业规划与转型',
                    status: 'upcoming',
                    statusText: '即将开始',
                    date: '2023-05-15 15:00',
                    location: '线上',
                    participants: 412
                }
            ],
            openday: [
                {
                    id: 'o1',
                    title: '微软中国研发中心开放日',
                    img: 'img/activity-openday1.jpg',
                    alt: '微软中国研发中心开放日',
                    status: 'upcoming',
                    statusText: '即将开始',
                    date: '2023-05-20 10:00',
                    location: '北京市海淀区',
                    participants: 150
                },
                {
                    id: 'o2',
                    title: '阿里巴巴杭州总部参观日',
                    img: 'img/activity-openday2.jpg',
                    alt: '阿里巴巴杭州总部参观日',
                    status: 'upcoming',
                    statusText: '即将开始',
                    date: '2023-05-25 09:30',
                    location: '杭州市余杭区',
                    participants: 200
                },
                {
                    id: 'o3',
                    title: '华为深圳坂田基地开放日',
                    img: 'img/activity-openday3.jpg',
                    alt: '华为深圳坂田基地开放日',
                    status: 'ended',
                    statusText: '已结束',
                    date: '2023-04-10 10:00',
                    location: '深圳市龙岗区',
                    participants: 320
                }
            ],
            competition: [
                {
                    id: 'c1',
                    title: '2023全国大学生人工智能创新大赛',
                    img: 'img/activity-competition1.jpg',
                    alt: '2023全国大学生人工智能创新大赛',
                    status: 'ongoing',
                    statusText: '进行中',
                    date: '2023-04-01 至 2023-06-30',
                    location: '全国各赛区',
                    participants: 5280
                },
                {
                    id: 'c2',
                    title: '互联网+创新创业大赛',
                    img: 'img/activity-competition2.jpg',
                    alt: '互联网+创新创业大赛',
                    status: 'upcoming',
                    statusText: '即将开始',
                    date: '2023-05-15 至 2023-08-30',
                    location: '全国各高校',
                    participants: 8650
                },
                {
                    id: 'c3',
                    title: '算法挑战赛：高效求解旅行商问题',
                    img: 'img/activity-competition3.jpg',
                    alt: '算法挑战赛：高效求解旅行商问题',
                    status: 'ongoing',
                    statusText: '进行中',
                    date: '2023-04-20 至 2023-05-20',
                    location: '线上',
                    participants: 1240
                }
            ]
        };
        
        // 获取当前类型的活动数据
        const activities = activityData[activityType];
        if (!activities || activities.length === 0) return;
        
        // 清空现有的类型相同的活动卡片
        document.querySelectorAll(`.activity-card[data-type="${activityType}"]`).forEach(card => {
            card.remove();
        });
        
        // 创建活动卡片并添加到容器中
        activities.forEach(activity => {
            // 创建卡片元素
            const card = document.createElement('a');
            card.href = `pages/activity-detail.html?id=${activity.id}`;
            card.className = 'card activity-card';
            card.setAttribute('data-type', activityType);
            card.style.display = 'block';
            
            // 设置卡片内容
            card.innerHTML = `
                <div class="card-img">
                    <img src="${activity.img}" alt="${activity.alt}">
                    <span class="status ${activity.status}">${activity.statusText}</span>
                </div>
                <div class="card-body">
                    <h3>${activity.title}</h3>
                    <p class="info"><i class="bi bi-calendar"></i> ${activity.date}</p>
                    <p class="info"><i class="bi bi-geo-alt"></i> ${activity.location}</p>
                    <div class="card-footer">
                        <span class="participants"><i class="bi bi-people"></i> ${activity.participants}人参与</span>
                        <button class="like-btn"><i class="bi bi-heart"></i></button>
                    </div>
                </div>
            `;
            
            // 将卡片添加到容器
            container.appendChild(card);
        });
        
        // 重新绑定喜欢按钮事件
        initLikeButtons();
        
        // 处理新创建的图片加载错误
        handleImageErrors();
    }
}

// 筛选选项功能
function initFilterOptions() {
    const filterOptionContainers = document.querySelectorAll('.filter-options');
    
    filterOptionContainers.forEach(container => {
        const options = container.querySelectorAll('.filter-option');
        
        options.forEach(option => {
            option.addEventListener('click', function() {
                // 移除当前容器内所有选项的active类
                options.forEach(o => o.classList.remove('active'));
                // 为当前点击的选项添加active类
                this.classList.add('active');
                
                // 根据筛选条件过滤内容（实际项目中会有更复杂的逻辑）
                const selectedIndustry = document.querySelector('.filter-row:first-child .filter-option.active').textContent;
                const selectedSalary = document.querySelector('.filter-row:last-child .filter-option.active').textContent;
                
                // 这里可以添加实际的筛选逻辑
                console.log('筛选条件:', {行业: selectedIndustry, 薪资: selectedSalary});
            });
        });
    });
}

// 收藏按钮功能
function initLikeButtons() {
    const likeButtons = document.querySelectorAll('.like-btn');
    
    likeButtons.forEach(button => {
        button.addEventListener('click', function() {
            // 切换active类来改变图标颜色
            this.classList.toggle('active');
            
            // 切换图标
            const icon = this.querySelector('i');
            if (icon.classList.contains('bi-heart')) {
                icon.classList.remove('bi-heart');
                icon.classList.add('bi-heart-fill');
                
                // 添加收藏动画
                addStarAnimation(this);
            } else {
                icon.classList.remove('bi-heart-fill');
                icon.classList.add('bi-heart');
            }
        });
    });
}

// 收藏星星动画
function addStarAnimation(element) {
    // 创建星星元素
    const star = document.createElement('div');
    star.className = 'star-animation';
    star.innerHTML = '<i class="bi bi-star-fill"></i>';
    
    // 设置星星样式
    star.style.position = 'absolute';
    star.style.color = '#ffc107';
    star.style.fontSize = '20px';
    star.style.zIndex = '1000';
    
    // 设置星星初始位置（按钮中心）
    const rect = element.getBoundingClientRect();
    star.style.left = rect.left + rect.width / 2 + 'px';
    star.style.top = rect.top + rect.height / 2 + 'px';
    
    // 将星星添加到body
    document.body.appendChild(star);
    
    // 设置星星动画
    setTimeout(() => {
        star.style.transition = 'all 0.5s ease-out';
        star.style.transform = 'translateY(-50px) scale(1.5)';
        star.style.opacity = '0';
    }, 10);
    
    // 动画结束后移除星星
    setTimeout(() => {
        document.body.removeChild(star);
    }, 600);
}

// 申请按钮功能
function initApplyButtons() {
    const applyButtons = document.querySelectorAll('.apply-btn');
    
    applyButtons.forEach(button => {
        button.addEventListener('click', function() {
            const jobTitle = this.closest('.card-body').querySelector('h3').textContent;
            const company = this.closest('.card-body').querySelector('.company-name').textContent;
            
            // 显示申请确认对话框
            if (confirm(`确定要申请 ${company} 的 ${jobTitle} 职位吗？`)) {
                // 模拟申请成功
                button.textContent = '已申请';
                button.disabled = true;
                button.style.backgroundColor = '#999';
                
                // 实际项目中这里会发送申请请求到服务器
                console.log('申请职位:', {公司: company, 职位: jobTitle});
            }
        });
    });
}

// 咨询按钮功能
function initConsultButtons() {
    const consultButtons = document.querySelectorAll('.consult-btn');
    
    consultButtons.forEach(button => {
        button.addEventListener('click', function() {
            const agentName = this.closest('.card-body').querySelector('h3').textContent;
            const agentTitle = this.closest('.card-body').querySelector('.title').textContent;
            
            // 显示预约确认对话框
            if (confirm(`确定要预约 ${agentName}（${agentTitle}）的咨询服务吗？`)) {
                // 模拟预约成功
                this.textContent = '已预约';
                this.disabled = true;
                this.style.backgroundColor = '#999';
                
                // 实际项目中这里会发送预约请求到服务器
                console.log('预约咨询:', {经纪人: agentName, 职位: agentTitle});
            }
        });
    });
}

// 底部Tab导航切换
document.addEventListener('DOMContentLoaded', function() {
    // 初始化底部导航栏
    initTabBar();
    
    // 处理搜索框
    const searchInput = document.querySelector('.search-bar input');
    
    if (searchInput) {
        searchInput.addEventListener('keypress', function(e) {
            if (e.key === 'Enter') {
                const searchText = this.value.trim();
                if (searchText) {
                    // 实际项目中会跳转到搜索结果页面
                    alert(`搜索 "${searchText}" 的结果正在开发中，敬请期待！`);
                    console.log('搜索:', searchText);
                }
            }
        });
    }
    
    // 模拟数据加载动画
    // 添加加载动画类
    document.body.classList.add('loading');
    
    // 模拟数据加载延迟
    setTimeout(() => {
        // 移除加载动画类
        document.body.classList.remove('loading');
    }, 800);
});

// 实现下拉刷新功能（简化版）
let startY = 0;
let pullDistance = 0;
const maxPullDistance = 100;
const refreshThreshold = 60;
let isPulling = false;
let isRefreshing = false;

document.addEventListener('touchstart', function(e) {
    // 只有在页面顶部才能下拉刷新
    if (window.scrollY === 0) {
        startY = e.touches[0].clientY;
        isPulling = true;
    }
});

document.addEventListener('touchmove', function(e) {
    if (!isPulling || isRefreshing) return;
    
    const currentY = e.touches[0].clientY;
    pullDistance = Math.min(maxPullDistance, currentY - startY);
    
    if (pullDistance > 0) {
        e.preventDefault();
        const mainContent = document.querySelector('.main-content');
        mainContent.style.transform = `translateY(${pullDistance}px)`;
    }
});

document.addEventListener('touchend', function() {
    if (!isPulling || isRefreshing) return;
    
    const mainContent = document.querySelector('.main-content');
    
    if (pullDistance >= refreshThreshold) {
        // 触发刷新
        isRefreshing = true;
        
        // 显示刷新动画
        mainContent.style.transform = `translateY(50px)`;
        
        // 模拟数据刷新
        setTimeout(() => {
            // 恢复页面位置
            mainContent.style.transition = 'transform 0.3s ease';
            mainContent.style.transform = 'translateY(0)';
            
            // 重置状态
            setTimeout(() => {
                mainContent.style.transition = '';
                isPulling = false;
                isRefreshing = false;
                pullDistance = 0;
            }, 300);
            
            // 显示刷新成功提示
            showToast('刷新成功');
            
        }, 1000);
    } else {
        // 未达到刷新阈值，恢复页面位置
        mainContent.style.transition = 'transform 0.3s ease';
        mainContent.style.transform = 'translateY(0)';
        
        setTimeout(() => {
            mainContent.style.transition = '';
            isPulling = false;
            pullDistance = 0;
        }, 300);
    }
});

// 显示提示信息
function showToast(message) {
    // 创建提示框元素
    const toast = document.createElement('div');
    toast.className = 'toast';
    toast.textContent = message;
    
    // 设置提示框样式
    toast.style.position = 'fixed';
    toast.style.top = '60px';
    toast.style.left = '50%';
    toast.style.transform = 'translateX(-50%)';
    toast.style.padding = '8px 16px';
    toast.style.backgroundColor = 'rgba(0, 0, 0, 0.7)';
    toast.style.color = '#fff';
    toast.style.borderRadius = '4px';
    toast.style.zIndex = '1000';
    toast.style.opacity = '0';
    toast.style.transition = 'opacity 0.3s ease';
    
    // 将提示框添加到body
    document.body.appendChild(toast);
    
    // 显示提示框
    setTimeout(() => {
        toast.style.opacity = '1';
    }, 10);
    
    // 2秒后隐藏并移除提示框
    setTimeout(() => {
        toast.style.opacity = '0';
        setTimeout(() => {
            document.body.removeChild(toast);
        }, 300);
    }, 2000);
}

// Tab栏功能
function initTabBar() {
    const tabItems = document.querySelectorAll('.tab-bar .tab-item');
    
    tabItems.forEach((tab, index) => {
        tab.addEventListener('click', function() {
            // 移除所有标签的active类
            tabItems.forEach(t => t.classList.remove('active'));
            // 为当前点击的标签添加active类
            this.classList.add('active');
            
            // 根据点击的标签执行相应操作
            const pageName = this.querySelector('span').textContent;
            
            // 获取当前页面路径
            const currentPath = window.location.pathname;
            // 判断是否在首页
            const isIndex = currentPath.endsWith('index.html') || currentPath.endsWith('/') || currentPath.endsWith('/jwyz/');
            // 获取适当的路径前缀
            const prefix = isIndex ? '' : '../';
            
            // 根据索引跳转到不同页面
            switch(index) {
                case 0: // 首页
                    if (!isIndex) {
                        window.location.href = `${prefix}index.html`;
                    }
                    break;
                case 1: // 发现
                    window.location.href = `${prefix}pages/discover.html`;
                    break;
                case 2: // 经纪人
                    window.location.href = `${prefix}pages/agents.html`;
                    break;
                case 3: // 我的
                    window.location.href = `${prefix}pages/profile.html`;
                    break;
            }
        });
    });
}

// 预加载图片集合
const preloadedImages = {
    // 活动相关图片
    activities: [
        'https://images.unsplash.com/photo-1540317580384-e5d43867caa6?w=600&h=400&auto=format&fit=crop',
        'https://images.unsplash.com/photo-1588702547923-7093a6c3ba33?w=600&h=400&auto=format&fit=crop',
        'https://images.unsplash.com/photo-1573164574511-73c773193279?w=600&h=400&auto=format&fit=crop',
        'https://images.unsplash.com/photo-1559223607-a43f990c095d?w=600&h=400&auto=format&fit=crop',
        'https://images.unsplash.com/photo-1558008258-3256797b43f3?w=600&h=400&auto=format&fit=crop'
    ],
    // 院校图片
    schools: [
        'https://images.unsplash.com/photo-1592280771190-3e2e4d571952?w=600&h=400&auto=format&fit=crop',
        'https://images.unsplash.com/photo-1607237138185-eedd9c632b0b?w=600&h=400&auto=format&fit=crop',
        'https://images.unsplash.com/photo-1615876234886-fd9a39fda97f?w=600&h=400&auto=format&fit=crop',
        'https://images.unsplash.com/photo-1584697964358-3e14ca57658b?w=600&h=400&auto=format&fit=crop',
        'https://images.unsplash.com/photo-1541339907198-e08756dedf3f?w=600&h=400&auto=format&fit=crop'
    ],
    // 企业图片
    companies: [
        'https://images.unsplash.com/photo-1556761175-5973dc0f32e7?w=600&h=400&auto=format&fit=crop',
        'https://images.unsplash.com/photo-1497366811353-6870744d04b2?w=600&h=400&auto=format&fit=crop',
        'https://images.unsplash.com/photo-1604328698692-f76ea9498e76?w=600&h=400&auto=format&fit=crop',
        'https://images.unsplash.com/photo-1486406146926-c627a92ad1ab?w=600&h=400&auto=format&fit=crop',
        'https://images.unsplash.com/photo-1622126807280-9b5b32b28e77?w=600&h=400&auto=format&fit=crop'
    ],
    // 公司Logo图片
    logos: [
        'https://images.unsplash.com/photo-1560179707-f14e90ef3623?w=300&h=300&auto=format&fit=crop',
        'https://images.unsplash.com/photo-1611162617213-7d7a39e9b1d7?w=300&h=300&auto=format&fit=crop',
        'https://images.unsplash.com/photo-1599305445671-ac291c95aaa9?w=300&h=300&auto=format&fit=crop',
        'https://images.unsplash.com/photo-1581287053822-fd7bf4f4bfec?w=300&h=300&auto=format&fit=crop',
        'https://images.unsplash.com/photo-1588702547919-26089e690ecc?w=300&h=300&auto=format&fit=crop'
    ],
    // 职业经纪人头像 - 使用固定头像，而非随机生成
    agents: [
        'https://images.unsplash.com/photo-1580489944761-15a19d654956?w=300&h=300&auto=format&fit=crop',
        'https://images.unsplash.com/photo-1500648767791-00dcc994a43e?w=300&h=300&auto=format&fit=crop',
        'https://images.unsplash.com/photo-1607746882042-944635dfe10e?w=300&h=300&auto=format&fit=crop',
        'https://images.unsplash.com/photo-1472099645785-5658abf4ff4e?w=300&h=300&auto=format&fit=crop',
        'https://images.unsplash.com/photo-1573497019940-1c28c88b4f3e?w=300&h=300&auto=format&fit=crop',
        'https://images.unsplash.com/photo-1438761681033-6461ffad8d80?w=300&h=300&auto=format&fit=crop',
        'https://images.unsplash.com/photo-1544005313-94ddf0286df2?w=300&h=300&auto=format&fit=crop',
        'https://images.unsplash.com/photo-1531427186611-ecfd6d936c79?w=300&h=300&auto=format&fit=crop'
    ],
    // 用户头像
    avatars: [
        'https://images.unsplash.com/photo-1535713875002-d1d0cf377fde?w=300&h=300&auto=format&fit=crop',
        'https://images.unsplash.com/photo-1599566150163-29194dcaad36?w=300&h=300&auto=format&fit=crop',
        'https://images.unsplash.com/photo-1527980965255-d3b416303d12?w=300&h=300&auto=format&fit=crop',
        'https://images.unsplash.com/photo-1570295999919-56ceb5ecca61?w=300&h=300&auto=format&fit=crop',
        'https://images.unsplash.com/photo-1633332755192-727a05c4013d?w=300&h=300&auto=format&fit=crop'
    ],
    // 特定类型活动的图片
    activityTypes: {
        product: [
            'https://images.unsplash.com/photo-1552664730-d307ca884978?w=600&h=400&auto=format&fit=crop',
            'https://images.unsplash.com/photo-1542744095-fcf48d80b0fd?w=600&h=400&auto=format&fit=crop',
            'https://images.unsplash.com/photo-1565688534245-05d6b5be184a?w=600&h=400&auto=format&fit=crop'
        ],
        recruitment: [
            'https://images.unsplash.com/photo-1560264280-88b68371db39?w=600&h=400&auto=format&fit=crop',
            'https://images.unsplash.com/photo-1560250097-0b93528c311a?w=600&h=400&auto=format&fit=crop',
            'https://images.unsplash.com/photo-1454165804606-c3d57bc86b40?w=600&h=400&auto=format&fit=crop'
        ],
        competition: [
            'https://images.unsplash.com/photo-1517245386807-bb43f82c33c4?w=600&h=400&auto=format&fit=crop',
            'https://images.unsplash.com/photo-1504639725590-34d0984388bd?w=600&h=400&auto=format&fit=crop',
            'https://images.unsplash.com/photo-1501504905252-473c47e087f8?w=600&h=400&auto=format&fit=crop'
        ]
    }
};

// 处理图片加载错误
function handleImageErrors() {
    // 为所有图片添加加载错误处理
    const images = document.querySelectorAll('img');
    
    // 生成随机ID的函数，用于确保获取不同的图片
    const generateRandomId = () => Math.floor(Math.random() * 100) + 1;
    
    // 高质量特定主题图片集合
    const highQualityImages = {
        activities: {
            all: [
                'https://source.unsplash.com/featured/800x600/?workshop,seminar',
                'https://source.unsplash.com/featured/800x600/?conference,event',
                'https://source.unsplash.com/featured/800x600/?career,fair',
                'https://source.unsplash.com/featured/800x600/?hackathon',
                'https://source.unsplash.com/featured/800x600/?training,professional'
            ],
            product: [
                'https://source.unsplash.com/featured/800x600/?tech,product',
                'https://source.unsplash.com/featured/800x600/?workshop,design',
                'https://source.unsplash.com/featured/800x600/?product,management'
            ],
            recruitment: [
                'https://source.unsplash.com/featured/800x600/?career,fair',
                'https://source.unsplash.com/featured/800x600/?recruitment,event',
                'https://source.unsplash.com/featured/800x600/?campus,interview'
            ],
            competition: [
                'https://source.unsplash.com/featured/800x600/?coding,competition',
                'https://source.unsplash.com/featured/800x600/?hackathon,prize',
                'https://source.unsplash.com/featured/800x600/?contest,award'
            ]
        },
        schools: [
            'https://source.unsplash.com/featured/800x600/?university,campus',
            'https://source.unsplash.com/featured/800x600/?college,education',
            'https://source.unsplash.com/featured/800x600/?campus,building',
            'https://source.unsplash.com/featured/800x600/?library,university',
            'https://source.unsplash.com/featured/800x600/?graduation,ceremony'
        ],
        companies: [
            'https://source.unsplash.com/featured/800x600/?office,modern',
            'https://source.unsplash.com/featured/800x600/?corporate,building',
            'https://source.unsplash.com/featured/800x600/?tech,company',
            'https://source.unsplash.com/featured/800x600/?startup,office',
            'https://source.unsplash.com/featured/800x600/?business,skyline'
        ],
        logos: [
            'https://source.unsplash.com/featured/300x300/?logo,brand',
            'https://source.unsplash.com/featured/300x300/?company,logo',
            'https://source.unsplash.com/featured/300x300/?corporate,identity',
            'https://source.unsplash.com/featured/300x300/?tech,brand',
            'https://source.unsplash.com/featured/300x300/?business,icon'
        ]
    };
    
    // 自动触发所有图片的加载检查，不等待图片加载错误事件
    images.forEach(img => {
        // 跳过已经成功加载的图片
        if (img.complete && img.naturalWidth > 0 && img.src && !img.src.includes('placeholder') && !img.src.includes('data:image')) {
            return;
        }
        
        // 获取图片尺寸
        const width = img.clientWidth || img.width || img.getAttribute('width') || 300;
        const height = img.clientHeight || img.height || img.getAttribute('height') || 300;
        
        // 获取图片类别和特定类型
        const { category, specificType } = getCategoryAndType(img);
        
        // 生成随机ID用于避免缓存
        const randomId = generateRandomId();
        
        // 选择图片源
        let imageSrc = selectImageSource(category, specificType, width, height, randomId);
        
        // 设置图片源并应用样式
        applyImageStyles(img, imageSrc, category);
    });
    
    // 获取图片类别和特定类型
    function getCategoryAndType(img) {
        let category = '';
        let specificType = '';
        
        // 获取alt文本以确定具体内容类型
        const altText = img.getAttribute('alt') || '';
        
        // 判断图片所属模块和类别
        if (img.closest('.activity-card')) {
            category = 'activities';
            if (altText.includes('产品') || altText.includes('互联网')) {
                specificType = 'product';
            } else if (altText.includes('招聘') || altText.includes('宣讲')) {
                specificType = 'recruitment';
            } else if (altText.includes('比赛') || altText.includes('大赛') || altText.includes('竞赛')) {
                specificType = 'competition';
            }
        } else if (img.closest('.institution-card') && (altText.includes('大学') || altText.includes('学院'))) {
            category = 'schools';
        } else if (img.closest('.institution-card') && !altText.includes('大学')) {
            category = 'companies';
        } else if (img.classList.contains('company-logo') || img.parentElement.classList.contains('company-logo')) {
            category = 'logos';
        } else if (img.closest('.agent-card') || img.classList.contains('agent-avatar')) {
            category = 'agents';
        } else if (img.classList.contains('avatar') || img.parentElement.classList.contains('avatar-container') || img.classList.contains('user-avatar')) {
            category = 'avatars';
        } else if (img.classList.contains('activity-img')) {
            category = 'activities';
            // 尝试从alt或附近元素确定活动类型
            const activityTitle = img.getAttribute('alt') || '';
            if (activityTitle.includes('产品') || activityTitle.includes('互联网')) {
                specificType = 'product';
            } else if (activityTitle.includes('招聘') || activityTitle.includes('宣讲')) {
                specificType = 'recruitment';
            } else if (activityTitle.includes('比赛') || activityTitle.includes('大赛') || activityTitle.includes('竞赛')) {
                specificType = 'competition';
            }
        } else if (img.classList.contains('school-logo')) {
            category = 'schools';
        }
        
        return { category, specificType };
    }
    
    // 选择图片源
    function selectImageSource(category, specificType, width, height, randomId) {
        let imageSrc = '';
        
        // 为不同类型的图片选择更好的替代图片
        if (category === 'avatars') {
            // 使用专业的头像服务
            imageSrc = `https://i.pravatar.cc/${width}?img=${randomId}`;
        } else if (category === 'activities') {
            if (specificType && highQualityImages.activities[specificType]) {
                // 从特定活动类型集合中选择
                const typeImages = highQualityImages.activities[specificType];
                imageSrc = typeImages[randomId % typeImages.length];
            } else {
                // 从通用活动集合中选择
                const allActivityImages = highQualityImages.activities.all;
                imageSrc = allActivityImages[randomId % allActivityImages.length];
            }
        } else if (category === 'schools') {
            const schoolImages = highQualityImages.schools;
            imageSrc = schoolImages[randomId % schoolImages.length];
        } else if (category === 'companies') {
            const companyImages = highQualityImages.companies;
            imageSrc = companyImages[randomId % companyImages.length];
        } else if (category === 'logos') {
            const logoImages = highQualityImages.logos;
            imageSrc = logoImages[randomId % logoImages.length];
        } else if (category === 'agents') {
            imageSrc = `https://i.pravatar.cc/${width}?img=${randomId + 50}`; // 使用不同范围的随机ID
        } else {
            // 默认图片
            imageSrc = `https://source.unsplash.com/featured/${width}x${height}/?professional,business&sig=${randomId}`;
        }
        
        return imageSrc;
    }
    
    // 应用图片样式
    function applyImageStyles(img, imageSrc, category) {
        // 设置图片源
        img.src = imageSrc;
        
        // 设置样式
        if (category === 'avatars' || category === 'agents') {
            img.style.objectFit = 'cover';
            img.style.borderRadius = '50%';
        } else {
            img.style.objectFit = 'cover';
        }
        
        // 增加图片加载质量和显示效果
        img.setAttribute('loading', 'eager');
        img.style.backgroundColor = '#f0f0f0';
        
        // 添加错误处理，以防图片加载失败
        img.addEventListener('error', function() {
            // 使用备用图片服务
            this.src = `https://picsum.photos/${width}/${height}?random=${Math.random()}`;
        });
    }
    
    // 为所有图片添加加载错误处理
    images.forEach(img => {
        img.addEventListener('error', function() {
            const width = this.width || this.getAttribute('width') || 300;
            const height = this.height || this.getAttribute('height') || 300;
            const { category, specificType } = getCategoryAndType(this);
            const randomId = generateRandomId();
            const imageSrc = selectImageSource(category, specificType, width, height, randomId);
            applyImageStyles(this, imageSrc, category);
        });
    });
}

// 预加载首页所需图片
function preloadImages() {
    // 合并所有需要预加载的图片
    const allImages = [].concat(
        preloadedImages.activities,
        preloadedImages.schools,
        preloadedImages.companies,
        preloadedImages.logos,
        preloadedImages.agents,
        preloadedImages.avatars
    );
    
    // 预加载图片
    allImages.forEach(src => {
        const img = new Image();
        img.src = src;
    });
}

/**
 * 创建点击涟漪效果
 */
function createRippleEffect(element, event) {
    const ripple = document.createElement('div');
    ripple.className = 'ripple-effect';
    
    const rect = element.getBoundingClientRect();
    const x = event.clientX - rect.left;
    const y = event.clientY - rect.top;
    
    ripple.style.left = `${x}px`;
    ripple.style.top = `${y}px`;
    
    element.appendChild(ripple);
    
    setTimeout(() => {
        ripple.remove();
    }, 600);
}

/**
 * 初始化院校和企业卡片的点击事件
 */
function initInstitutionCardEvents() {
    // 获取所有院校卡片
    const schoolCards = document.querySelectorAll('.schools-container .institution-card');
    schoolCards.forEach(card => {
        card.addEventListener('click', function(e) {
            // 添加涟漪效果
            createRippleEffect(this, e);
            
            // 防止a标签的默认行为
            e.preventDefault();
            const href = this.getAttribute('href');
            
            // 延迟导航以展示涟漪效果
            if (href) {
                setTimeout(() => {
                    window.location.href = href;
                }, 300);
            }
        });
    });

    // 获取所有企业卡片
    const companyCards = document.querySelectorAll('.companies-container .institution-card');
    companyCards.forEach(card => {
        card.addEventListener('click', function(e) {
            // 添加涟漪效果
            createRippleEffect(this, e);
            
            // 防止a标签的默认行为
            e.preventDefault();
            const href = this.getAttribute('href');
            
            // 延迟导航以展示涟漪效果
            if (href) {
                setTimeout(() => {
                    window.location.href = href;
                }, 300);
            }
        });
    });
}

/**
 * 页面滑动过渡动画控制
 */

// 记录页面滑动方向
let lastNavigationDirection = '';

/**
 * 初始化页面过渡动画
 */
function initPageTransitions() {
    // 创建页面过渡容器，如果尚未存在
    if (!document.querySelector('.page-transition-container')) {
        const container = document.createElement('div');
        container.className = 'page-transition-container';
        document.body.appendChild(container);
        
        // 添加页面过渡样式
        addPageTransitionStyles();
    }
    
    // 处理所有链接点击
    document.addEventListener('click', function(e) {
        // 查找最接近的链接元素
        const link = e.target.closest('a');
        
        // 如果点击的是链接且是站内链接
        if (link && link.href && link.href.includes(window.location.hostname) && 
            !link.getAttribute('target') && !e.ctrlKey && !e.metaKey) {
            
            // 阻止默认行为
            e.preventDefault();
            
            // 确定导航方向
            determineNavigationDirection(link.href);
            
            // 执行页面过渡动画
            performPageTransition(link.href);
        }
    });
    
    // 添加页面可见性初始化
    document.body.classList.add('page-visible');
}

/**
 * 添加页面过渡样式
 */
function addPageTransitionStyles() {
    // 检查是否已添加页面过渡样式
    if (document.getElementById('page-transition-styles')) return;
    
    // 创建style元素
    const style = document.createElement('style');
    style.id = 'page-transition-styles';
    
    // 添加CSS规则
    style.textContent = `
        .page-transition-container {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background-color: var(--primary-color, #4a6fee);
            z-index: 10000;
            transform: translateX(-100%);
            pointer-events: none;
        }
        
        .page-transition-container.slide-in-left {
            animation: slideInLeft 0.5s forwards;
        }
        
        .page-transition-container.slide-out-right {
            animation: slideOutRight 0.5s forwards;
        }
        
        .page-transition-container.slide-in-right {
            animation: slideInRight 0.5s forwards;
        }
        
        .page-transition-container.slide-out-left {
            animation: slideOutLeft 0.5s forwards;
        }
        
        @keyframes slideInLeft {
            from { transform: translateX(-100%); }
            to { transform: translateX(0); }
        }
        
        @keyframes slideOutRight {
            from { transform: translateX(0); }
            to { transform: translateX(100%); }
        }
        
        @keyframes slideInRight {
            from { transform: translateX(100%); }
            to { transform: translateX(0); }
        }
        
        @keyframes slideOutLeft {
            from { transform: translateX(0); }
            to { transform: translateX(-100%); }
        }
        
        .app-container {
            transition: transform 0.3s ease, opacity 0.3s ease;
        }
        
        .app-container.slide-left {
            transform: translateX(-30px);
            opacity: 0;
        }
        
        .app-container.slide-right {
            transform: translateX(30px);
            opacity: 0;
        }
        
        .app-container.slide-up {
            transform: translateY(-30px);
            opacity: 0;
        }
        
        .app-container.slide-down {
            transform: translateY(30px);
            opacity: 0;
        }
    `;
    
    // 添加到文档头部
    document.head.appendChild(style);
}

/**
 * 确定导航方向
 * @param {string} targetUrl - 目标页面URL
 */
function determineNavigationDirection(targetUrl) {
    // 获取当前路径和目标路径
    const currentPath = window.location.pathname;
    const targetPath = new URL(targetUrl).pathname;
    
    // 定义页面层级，数字越大表示层级越深
    const pageHierarchy = {
        '/jwyz/': 1,
        '/jwyz/index.html': 1,
        '/jwyz/pages/discover.html': 2,
        '/jwyz/pages/agents.html': 2,
        '/jwyz/pages/profile.html': 2,
        '/jwyz/pages/activities.html': 3,
        '/jwyz/pages/internships.html': 3,
        '/jwyz/pages/institutions.html': 3,
        '/jwyz/pages/activity-detail.html': 4,
        '/jwyz/pages/internship-detail.html': 4,
        '/jwyz/pages/school-detail.html': 4,
        '/jwyz/pages/company-detail.html': 4,
        '/jwyz/pages/article-details.html': 4
    };
    
    // 获取路径层级，如果未定义则默认为最深层级+1
    const currentHierarchy = pageHierarchy[currentPath] || 5;
    const targetHierarchy = pageHierarchy[targetPath] || 5;
    
    // 根据层级关系确定导航方向
    if (targetHierarchy > currentHierarchy) {
        // 向更深层级跳转时，向左滑动
        lastNavigationDirection = 'left';
    } else if (targetHierarchy < currentHierarchy) {
        // 向更浅层级跳转时，向右滑动
        lastNavigationDirection = 'right';
    } else {
        // 同级导航时，使用底部导航栏位置判断
        const tabBar = document.querySelector('.tab-bar');
        if (tabBar) {
            const currentTab = tabBar.querySelector('.tab-item.active');
            let targetTab = null;
            
            // 根据目标路径查找对应的标签
            if (targetPath.includes('index.html') || targetPath.endsWith('/jwyz/')) {
                targetTab = tabBar.querySelector('.tab-item:nth-child(1)');
            } else if (targetPath.includes('discover.html')) {
                targetTab = tabBar.querySelector('.tab-item:nth-child(2)');
            } else if (targetPath.includes('agents.html')) {
                targetTab = tabBar.querySelector('.tab-item:nth-child(3)');
            } else if (targetPath.includes('profile.html')) {
                targetTab = tabBar.querySelector('.tab-item:nth-child(4)');
            }
            
            if (currentTab && targetTab) {
                // 获取标签的索引
                const currentIndex = Array.from(tabBar.querySelectorAll('.tab-item')).indexOf(currentTab);
                const targetIndex = Array.from(tabBar.querySelectorAll('.tab-item')).indexOf(targetTab);
                
                // 根据索引确定方向
                if (targetIndex > currentIndex) {
                    lastNavigationDirection = 'left';
                } else {
                    lastNavigationDirection = 'right';
                }
            } else {
                // 默认向左滑动
                lastNavigationDirection = 'left';
            }
        } else {
            // 默认向左滑动
            lastNavigationDirection = 'left';
        }
    }
    
    // 将导航方向保存到sessionStorage
    sessionStorage.setItem('navigationDirection', lastNavigationDirection);
}

/**
 * 执行页面过渡动画
 * @param {string} targetUrl - 目标页面URL
 */
function performPageTransition(targetUrl) {
    const container = document.querySelector('.page-transition-container');
    const appContainer = document.querySelector('.app-container');
    
    // 如果找不到容器，直接跳转
    if (!container || !appContainer) {
        window.location.href = targetUrl;
        return;
    }
    
    // 根据导航方向添加不同的动画类
    if (lastNavigationDirection === 'left') {
        // 向左滑动（向前导航）
        container.classList.add('slide-in-left');
        appContainer.classList.add('slide-left');
    } else {
        // 向右滑动（向后导航）
        container.classList.add('slide-in-right');
        appContainer.classList.add('slide-right');
    }
    
    // 一段时间后跳转到目标页面
    setTimeout(() => {
        window.location.href = targetUrl;
    }, 300);
}

/**
 * 加载页面方向并应用相应动画
 */
function loadPageDirection() {
    // 从sessionStorage获取上一次的导航方向
    const direction = sessionStorage.getItem('navigationDirection');
    
    // 如果有方向信息
    if (direction) {
        const container = document.querySelector('.page-transition-container');
        const appContainer = document.querySelector('.app-container');
        
        // 如果找不到容器，直接返回
        if (!container || !appContainer) return;
        
        // 根据导航方向添加不同的动画类
        if (direction === 'left') {
            // 从右向左进入
            container.classList.add('slide-out-right');
            setTimeout(() => {
                container.classList.remove('slide-out-right');
            }, 500);
        } else {
            // 从左向右进入
            container.classList.add('slide-out-left');
            setTimeout(() => {
                container.classList.remove('slide-out-left');
            }, 500);
        }
        
        // 清除导航方向记录
        sessionStorage.removeItem('navigationDirection');
    }
}

/**
 * 处理滚动导航效果
 */
function handleScrollNavigation() {
    let lastScrollTop = 0;
    let ticking = false;
    const tabBar = document.querySelector('.tab-bar');
    
    // 如果没有底部导航栏，直接返回
    if (!tabBar) return;
    
    // 添加简单的滚动指示器
    addScrollIndicator();
    
    // 监听滚动事件
    window.addEventListener('scroll', function() {
        if (!ticking) {
            window.requestAnimationFrame(function() {
                // 获取滚动位置
                const scrollTop = window.pageYOffset || document.documentElement.scrollTop;
                
                // 向下滚动超过50px时隐藏底部导航栏，向上滚动时显示
                if (scrollTop > lastScrollTop && scrollTop > 100) {
                    // 向下滚动
                    tabBar.classList.add('tab-bar-hidden');
                } else if (scrollTop < lastScrollTop || scrollTop < 50) {
                    // 向上滚动或回到顶部
                    tabBar.classList.remove('tab-bar-hidden');
                }
                
                // 更新滚动指示器
                updateScrollIndicator(scrollTop);
                
                // 更新上一次滚动位置
                lastScrollTop = scrollTop;
                ticking = false;
            });
            
            ticking = true;
        }
    }, { passive: true });
    
    // 为导航栏添加淡入效果
    setTimeout(() => {
        tabBar.style.opacity = '1';
    }, 300);
}

/**
 * 添加滚动指示器
 */
function addScrollIndicator() {
    // 检查是否已存在滚动指示器
    if (document.getElementById('scroll-indicator')) return;
    
    // 创建滚动指示器
    const indicator = document.createElement('div');
    indicator.id = 'scroll-indicator';
    indicator.style.cssText = `
        position: fixed;
        top: 0;
        left: 0;
        height: 3px;
        background: linear-gradient(to right, #4a6fee, #a891ff);
        width: 0%;
        z-index: 2000;
        transition: width 0.2s ease-out;
        border-radius: 0 3px 3px 0;
    `;
    
    // 添加到文档
    document.body.appendChild(indicator);
}

/**
 * 更新滚动指示器
 * @param {number} scrollTop - 当前滚动位置
 */
function updateScrollIndicator(scrollTop) {
    const indicator = document.getElementById('scroll-indicator');
    if (!indicator) return;
    
    const winHeight = window.innerHeight;
    const docHeight = document.documentElement.scrollHeight;
    const scrollPercent = (scrollTop) / (docHeight - winHeight) * 100;
    
    indicator.style.width = `${scrollPercent}%`;
    
    // 变化颜色
    if (scrollPercent > 80) {
        indicator.style.background = 'linear-gradient(to right, #ff416c, #ff4b2b)';
    } else if (scrollPercent > 50) {
        indicator.style.background = 'linear-gradient(to right, #f7971e, #ffd200)';
    } else {
        indicator.style.background = 'linear-gradient(to right, #4a6fee, #a891ff)';
    }
} 